package com.freedom.monitor.myeye.config.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.thrift.TException;

import com.freedom.monitor.myeye.config.model.Count;
import com.freedom.monitor.myeye.config.model.User;
import com.freedom.monitor.myeye.config.utils.DbUtilsHelper;
import com.freedom.monitor.myeye.config.utils.RoleUtils;
import com.freedom.monitor.myeye.config.utils.SqlUtils;
import com.freedom.monitor.myeye.config.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;

//用户服务，比如登录
public class UserImpl implements UserConfigService.Iface {
	private static final Logger logger = Logger.getLogger(UserImpl.class);

	@Override
	public LoginUser login(String username, String password) throws TException {
		// 用户分2种，1种是系统级用户,还有1种是普通用户
		// 普通管理员权限目前为TODO状态
		logger.debug("ConfigServiceImpl.login received..username:" + username + " password:" + password);
		LoginUser result = loginFromUserTable(username, password);
		if (null == result || false == result.isSucceed()) {
			result = loginFromMemberTable(username, password);
		}
		return result;
	}

	private static LoginUser loginFromUserTable(String username, String password) throws TException {
		logger.debug("ConfigServiceImpl.loginFromUserTable received..username:" + username + " password:" + password);
		// 0)参数有效
		if (false == StringUtils.valid(username, password)) {
			return new LoginUser(false, "", null, -1, "invalid username/password");
		}
		username = username.trim();
		password = password.trim();
		// 1)查询有效
		String sql = String.format(SqlUtils.QUERY_SYSTEM_USER, username, password);
		logger.debug("begin to execute -> " + sql);
		User user = (User) DbUtilsHelper.queryOneObject(sql, User.class);
		logger.debug("after callback,user is " + user);
		if (null == user) {
			logger.warn("fail to find system user");
			return new LoginUser(false, "", null, -1, "fail to find system user");// 因为各种各样的原因，查询失败
		}
		// 2)说明确实有这个人
		// 2.1)更新token有效
		sql = SqlUtils.UPDATE_SYSTEM_USER;
		String token = RandomStringUtils.random(64, true, true);
		int result = DbUtilsHelper.updateOneObject(sql, token, user.getUserid());
		if (result <= 0) {
			logger.error("save token to system user fail...");
			return new LoginUser(false, "", null, -1, "save token to system user fail...");
		}
		logger.debug("affected rows-> " + result + " by-> " + sql + " token:" + token + " userId:" + user.getUserid());
		// 2.2)返回LoginUser给调用方
		return new LoginUser(true, user.getUserid(), token, user.getRole(), "");
	}

	private static LoginUser loginFromMemberTable(String username, String password) throws TException {
		logger.debug("ConfigServiceImpl.login received..username:" + username + " password:" + password);
		// 0)参数有效
		if (false == StringUtils.valid(username, password)) {
			return new LoginUser(false, "", null, -1, "invalid username/password");
		}
		username = username.trim();
		password = password.trim();
		// 1)查询有效
		String sql = String.format(SqlUtils.QUERY_COMMON_USER, username, password);
		logger.debug("begin to execute -> " + sql);
		User user = (User) DbUtilsHelper.queryOneObject(sql, User.class);
		logger.debug("after callback,user is " + user);
		if (null == user) {
			logger.warn("fail to find common user");
			return new LoginUser(false, "", null, -1, "fail to find common user");// 因为各种各样的原因，查询失败
		}
		// 2)说明确实有这个人
		// 2.1)更新token有效
		sql = SqlUtils.UPDATE_COMMON_USER;
		String token = RandomStringUtils.random(64, true, true);
		int result = DbUtilsHelper.updateOneObject(sql, token, user.getUserid());
		if (result <= 0) {
			logger.error("save common token to user fail...");
			return new LoginUser(false, "", null, -1, "save common token to user fail...");
		}
		logger.debug("affected rows-> " + result + " by-> " + sql + " token:" + token + " userId:" + user.getUserid());
		// 2.2)返回LoginUser给调用方
		return new LoginUser(true, user.getUserid(), token, user.getRole(), "");
	}

	public static void main(String[] args) {
		// 64位演示
		System.out.println(RandomStringUtils.random(64 - 13, true, true) + System.currentTimeMillis());
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserResult queryUser(int page, int rows) throws TException {
		logger.debug("ConfigServiceImpl.queryUser is invoked...");
		// 1)构造sql
		String sql = "select distinct id,userid,username,name,pwd,role,DATE_FORMAT(createtime,'%Y-%m-%d %k:%i:%s') as createTime,token from t_system_user ";
		sql += " order by createtime desc ";
		sql += " limit " + (page - 1) * rows + "," + rows;
		logger.info("sql ---> " + sql);
		// 2)开始查询
		List<User> users = (List<User>) DbUtilsHelper.queryManyObject(sql, User.class);
		if (null == users) {// 修正一下
			users = new ArrayList<User>();
		}
		// 3)构造返回结果
		UserResult userResult = new UserResult();
		userResult.setSucceed(true);
		for (User user : users) {
			com.freedom.monitor.myeye.config.service.User rpcUser = new com.freedom.monitor.myeye.config.service.User();
			rpcUser.setId(user.getId());
			rpcUser.setUserid(user.getUserid());
			rpcUser.setUsername(user.getUsername());
			rpcUser.setName(user.getName());
			rpcUser.setPwd(user.getPwd());
			rpcUser.setRole(user.getRole());
			rpcUser.setRoleName(RoleUtils.getRoleByInt(user.getRole()));
			rpcUser.setCreateTime(user.getCreateTime());
			rpcUser.setToken(user.getToken());
			userResult.addToUserList(rpcUser);
		}
		// 4)设置总数
		sql = "select count(*) as count from t_system_user ";
		Count count = (Count) DbUtilsHelper.queryOneObject(sql, Count.class);
		if (null != count) {
			userResult.setTotal(count.getCount());
		} else {
			userResult.setTotal(0);
		}
		// 5)返回结果
		return userResult;
	}

	@Override
	public boolean deleteUser(String id) throws TException {
		// 1)获得id
		// 2)构造sql
		String sql = "delete from t_system_user where userid=?";
		logger.info("to be delete sql--->" + sql + " " + id);
		// 3)执行sql
		int result = DbUtilsHelper.deleteOneObject(sql, id);
		return (1 == result);
	}

	@Override
	public boolean addUser(String username, String name, String pwd, int role) throws TException {
		try {
			// 1)构造sql
			String sql = "insert into t_system_user(userid,username,name,pwd,role) values(?,?,?,?,?) ";
			// 2)执行sql
			int result = DbUtilsHelper.insertOneObject(sql, RandomStringUtils.random(64, true, true), username, name,
					pwd, role);
			return (1 == result);
		} catch (Exception e) {
			return false;
		}

	}

	@Override
	public boolean editUser(String username, String name, String pwd, int role, String userid) throws TException {
		logger.debug("ConfigServiceImpl.editUser invoked...");
		try {
			String sql = "update t_system_user set username=?,name=?,pwd=?,role=? where userid=?";
			// 2)执行sql
			int result = DbUtilsHelper.updateOneObject(sql, username, name, pwd, role, userid);
			return (1 == result);
		} catch (Exception e) {
			return false;
		}
	}

	



}
